package com.train.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.system.dto.station.StationDTO;
import com.train.system.resp.station.StationPageResp;
import com.train.common.exception.GlobalException;
import com.train.common.enums.impl.BizExceptionEnums;
import com.train.common.resp.PageResp;
import com.train.system.resp.station.StationResp;
import com.train.system.dto.station.StationAddOrEditDTO;
import com.train.system.dto.station.StationPageDTO;
import com.train.system.mapper.StationMapper;
import com.train.system.po.StationPO;
import com.train.system.service.StationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author baitiaojun
* @description 针对表【station(乘车人)】的数据库操作Service实现
* @createDate 2025-02-14 19:37:18
*/
@Service
@RequiredArgsConstructor
public class StationServiceImpl extends ServiceImpl<StationMapper, StationPO>
    implements StationService {

    private final StationMapper stationMapper;

    @Override
    public void addOrEditStation(StationAddOrEditDTO stationAddOrEditDTO) {
        //校验id是否存在,判断是insert还是update
        if (stationAddOrEditDTO.getId() != null) {
            //如果是编辑,需要校验id记录是否存在
            if (!stationMapper.existsId(stationAddOrEditDTO.getId())) {
                throw new GlobalException(BizExceptionEnums.EXP_STATION_NOT_EXISTS);
            }

            //查询该站名下的id
            StationDTO stationDTO = stationMapper.getId(stationAddOrEditDTO.getName());

            //如果id不存在就直接更新, 如果id存在且已存在同名车站, 判断更新站名的车站和当前被更新的车站是同一个车站, 不是才校验
            if (stationDTO != null && !stationDTO.getId().equals(stationAddOrEditDTO.getId())) {
                //校验被更新车站的站名在其他车站中是否已存在
                if (stationMapper.exists(stationAddOrEditDTO.getName())) {
                    throw new GlobalException(BizExceptionEnums.EXP_STATION_EXISTS);
                }
            }
        } else {
            //新增校验车站是否已存在
            if (stationMapper.exists(stationAddOrEditDTO.getName())) {
                throw new GlobalException(BizExceptionEnums.EXP_STATION_EXISTS);
            }
        }

        StationPO stationPO = BeanUtil.copyProperties(stationAddOrEditDTO, StationPO.class);
        boolean isSaved = this.saveOrUpdate(stationPO);
        if (!isSaved) {
            throw new GlobalException(BizExceptionEnums.EXP_ADD_STATION);
        }
    }

    @Override
    public PageResp<StationPageResp> pageList(StationPageDTO stationPageDTO) {
        return stationMapper.pageList(stationPageDTO);
    }

    @Override
    public void remove(Long id) throws GlobalException {
        boolean isRemoved = this.removeById(id);
        if (!isRemoved) {
            throw new GlobalException(BizExceptionEnums.EXP_REMOVE_STATION);
        }
    }

    @Override
    public List<StationResp> allStation() {
        return stationMapper.selectAllStation();
    }
}




